package hasthi.actuators.impl;

import hasthi.actuators.RemoteHostProxy;
import hasthi.common.BaseContext;
import hasthi.common.HasthiException;
import hasthi.common.HasthiException.FaultCode;
import hasthi.common.constants.HasthiConstants;
import hasthi.container.SimpleMessageContext;
import hasthi.container.UnicastContianier;
import hasthi.manager.ExecuteCommandDocument;
import hasthi.manager.ExecuteCommandResponseDocument;
import hasthi.manager.ExecuteCommandDocument.ExecuteCommand;
import hasthi.manager.ExecuteCommandResponseDocument.ExecuteCommandResponse;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlbeans.XmlObject;


public class HostAgentBasedHostProxy implements RemoteHostProxy {
    private static Log log = LogFactory.getLog(HasthiConstants.LOGGER_NAME);
    private BaseContext baseContext;
    private UnicastContianier soapContainer;
    private String agentURL;

    public HostAgentBasedHostProxy(BaseContext context, String agentURL, UnicastContianier soapContainer) throws HasthiException {
            this.baseContext = context;
            this.agentURL = agentURL;
            this.soapContainer = soapContainer;
    }

    /* (non-Javadoc)
     * @see hasthi.tools.RemoteHostProxy#runCommand(java.lang.String, java.lang.String, java.lang.String[], java.lang.String, boolean, java.lang.String)
     */
    public String[] runCommand(String hostName, String command, String[] args, String workDir,
            boolean wait4Complete,String verificationString) throws HasthiException {
        ExecuteCommandDocument commandDocument = ExecuteCommandDocument.Factory.newInstance();
        ExecuteCommand commandObj = commandDocument.addNewExecuteCommand();
        commandObj.setCmd(command);
        commandObj.setWorkdir(workDir);
        commandObj.setVerification(verificationString);
        XmlObject response = soapContainer.sendReceive(new SimpleMessageContext(commandDocument,agentURL,"someaction"));
        ExecuteCommandResponse cmdResponse = ((ExecuteCommandResponseDocument)response).getExecuteCommandResponse();
        log.info("Stdout of "+ command + " is "+ cmdResponse.getStdouterr());
        return cmdResponse.getResponseParamsArray();
    }

 

    public URI copy(URI src, URI dest) throws HasthiException {
        //TODO we will eventually support URL based http get transfers
        throw new UnsupportedOperationException();
    }

    public URI copyToDir(URI src, URI destDir) throws HasthiException {
        try {
            URI destFile = new URI(destDir.toString() + "/" + new File(src.getPath()).getName());
            return copy(src, destFile);
        } catch (URISyntaxException e) {
            throw new HasthiException(e, FaultCode.InvaliedLocalArgumnet);
        }
    }

    public BaseContext getBaseContext() {
        return baseContext;
    }
}
